package dk.au.cs.bdsi.mail.activities;

import dk.au.cs.bdsi.core.activities.UpdateException;
import dk.au.cs.bdsi.core.representation.Identifier;
import dk.au.cs.bdsi.core.representation.ServiceUri;
import dk.au.cs.bdsi.mail.domain.Mail;
import dk.au.cs.bdsi.mail.domain.MailStatus;
import dk.au.cs.bdsi.mail.repositories.MailRepository;
import dk.au.cs.bdsi.mail.representation.MailRepresentation;

public class UpdateMailActivity {
	// TODO Make concurrent
	public MailRepresentation update(Mail message, ServiceUri requestUri) {
		// Updated message must have status 'NotSent' or 'Pending'
		if (message.getStatus() != MailStatus.NotSent 
				&& message.getStatus() != MailStatus.Pending) {
			throw new UpdateException();
		}
		
		// Retrieve current state of the message
		Identifier id = requestUri.getId();
		Mail currentMessage = MailRepository.current().get(id);
		
		// Ensure message exists and can be updated
		if (currentMessage == null) throw new NoSuchMailException();
		if (currentMessage.getStatus() != MailStatus.NotSent) throw new UpdateException();
		
		// TODO Perform validity check on user-supplied message
		
		MailRepository.current().store(id, message);
		return MailRepresentation.createResponseRepresentation(message, requestUri);
	}
}
